

#include "Core/Bullet.h"

#include "PaperSpriteComponent.h"
#include "Components/SphereComponent.h"
#include "Enemy/Enemy2D.h"

ABullet::ABullet()
{
	PrimaryActorTick.bCanEverTick = true;

	SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent"));
	BulletSprite = CreateDefaultSubobject<UPaperSpriteComponent>(TEXT("BulletSprite"));

	RootComponent = SphereComponent;
	BulletSprite->SetupAttachment(RootComponent);

	MovementDirection = FVector(1.0f, 0.0f, 0.0f);

	
}

void ABullet::BeginPlay()
{
	Super::BeginPlay();

	SphereComponent->OnComponentBeginOverlap.AddDynamic(this, &ABullet::OverlapBegin);
}

void ABullet::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (IsLaunched)
	{
		FVector DistanceToMove = MovementDirection * MovementSpeed * DeltaTime;
		FVector NewLocation = GetActorLocation() + DistanceToMove;
		SetActorLocation(NewLocation);
	}
}

void ABullet::Launch(FVector Direction, float Speed)
{
	if (IsLaunched) return;
	IsLaunched = true;
	MovementDirection = Direction;
	MovementSpeed = Speed;

	float DeleteTime = 10.0f;
	GetWorldTimerManager().SetTimer(DeleteTimer, this, &ABullet::OnDeleteTimerTimeout, 1.0f, false, DeleteTime);
}

void ABullet::OnDeleteTimerTimeout()
{
	Destroy();
}

void ABullet::OverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp,
	int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	AEnemy2D* Enemy =  Cast<AEnemy2D>(OtherActor);
	if (Enemy && Enemy->IsAlive)
	{
		DisableBullet();
		Enemy->Die();
	}
}

void ABullet::DisableBullet()
{
	if (IsDisabled) return;

	IsDisabled = true;
	SphereComponent->SetCollisionEnabled(ECollisionEnabled::NoCollision);
	BulletSprite->DestroyComponent();
	
}

